package com.github.web.controller;

import com.github.CommonConstant;
import com.github.dbutil.DBContextHolder;
import com.github.session.LocalSession;
import com.github.session.SObject;
import com.github.umgr.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping(value = "/")
public class WebController {

    private static Logger logger = Logger.getLogger(WebController.class.getName());

    @Autowired
    private UserService userService;


    @RequestMapping(value = "login", method = RequestMethod.GET, name = "login page")
    public String login() {
        return "login/login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST, name = "login")
    public String doLogin(String name, String password, HttpServletRequest request) {
        DBContextHolder.setDSType("ds1");
        if (userService.doLogin(name, password, request)) {
            logger.info("login success !");
            return "redirect:/index.html";
        }
        logger.debug("go to login page!");
        return "login/login";
    }


    @RequestMapping(value = "index.html", method = RequestMethod.GET, name = "index page")
    public String index() {
        logger.debug("goto index!");
        return "index";
    }


    @RequestMapping(value = "logout", name = "logout")
    public String logout(HttpServletRequest request) {
        SObject session = (SObject) request.getSession().getAttribute(CommonConstant.USER_LOGIN_SESSION);
        if (null != session) {
            logger.warn(session.getUname() + " logout!");
            request.getSession().setAttribute(CommonConstant.USER_LOGIN_SESSION, null);
            LocalSession.remove();
        }

        return "login/login";
    }
}
